import { useState, useEffect, useRef } from 'react';
import { message, Table, Button, Select, Modal } from 'antd';
import { activityEffect, campaigncodeList } from '@/services/operate';
import { uniqBy, debounce, isEmpty } from 'lodash';
import moment from 'moment';

import styles from './style.less';

interface Props {
  detail: any;
  queryForm: any;
  channel: string;
}

let timeout: ReturnType<typeof setTimeout> | null;
let currentValue: string;

const fetch = (value: string, callback: Function) => {
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  currentValue = value;

  const fake = async () => {
    const { code, data } = await campaigncodeList({
      brandName: 'KFC',
      campaignCode: value,
    });
    if (code === 200 && data) {
      const dataBro = data.map((item: any) => ({
        value: item,
        text: item,
      }));
      callback(dataBro);
    }

    //   const str = qs.stringify({
    //     code: 'utf-8',
    //     q: value,
    //   });
    //   jsonp(`https://suggest.taobao.com/sug?${str}`)
    //     .then((response: any) => response.json())
    //     .then((d: any) => {
    //       if (currentValue === value) {
    //         const { result } = d;
    //         const data = result.map((item: any) => ({
    //           value: item[0],
    //           text: item[0],
    //         }));
    //         callback(data);
    //       }
    //     });
  };
  timeout = setTimeout(fake, 300);
};

let dataTableBro: any = [];
let pageNo: number = 1;

const RenderExpandedRow: React.FC<Props> = ({ detail, channel, queryForm }) => {
  const [valueSelect, setValueSelect] = useState(null);
  const [option, setOption] = useState([]);
  const [dataTable, setDataTable] = useState<any>([]);
  const [addLoad, setAddLoad] = useState(false);
  const [numFlag, setNumFlag] = useState(0); // 标识---添加到第几列的后面
  const [expandLoad, setExpandLoad] = useState(false); // 展开table--loading
  const childDivRef = useRef<any>(null);
  const broDivRef = useRef<any>(null);
  const scrollableDivRef = useRef<any>(null);
  // 切换活动效果时，需要重置的有： dataTableBro\pageNo\scrollFlag
  // const [pageNo, setPageNo] = useState(1); // 活动效果--虚拟滚动的分页
  const [scrollFlag, setSrollFlag] = useState(true); // 是否展示--虚拟滚动

  // 查询活动效果
  const initQuery = async (isAddPageNo?: boolean) => {
    const params = {
      activityId: detail.activityId,
      pageNo: isAddPageNo && isAddPageNo === true ? pageNo + 1 : pageNo,
      channel: channel,
    };
    setExpandLoad(true);
    const { code, data } = await activityEffect(params);
    setExpandLoad(false);
    if (code === 200 && data) {
      // setPageNo(data.pageNo);
      pageNo = data.pageNo;
      data.rows.forEach((item: any, index: number) => {
        if (item.activityId === detail.activityId) {
          item.showRed = true;
          setNumFlag(index);
        } else {
          item.showRed = false;
        }
      });
      dataTableBro = uniqBy([...dataTableBro, ...data.rows], 'id');
      setDataTable(dataTableBro);
      if (data.totalPage > data.pageNo) {
        setSrollFlag(true);
      } else {
        setSrollFlag(false);
      }
    }
  };

  const debouncedHandle = debounce(async () => {
    // 在这里执行你想要的操作
    if (scrollFlag) {
      initQuery(true);
    }
  }, 500);

  const handleScroll = () => {
    if (childDivRef.current) {
      const div1Rect = childDivRef.current.getBoundingClientRect();
      const div2Rect = broDivRef.current.getBoundingClientRect();
      const verticalDistance = div2Rect.top - div1Rect.top;
      if (10 > verticalDistance && verticalDistance > -10) {
        debouncedHandle();
      }
    }
  };

  useEffect(() => {
    if (scrollableDivRef && scrollableDivRef.current) {
      const scrollableDivRefBro = scrollableDivRef.current;
      // 在组件挂载时和滚动时执行计算距离的函数
      handleScroll();
      scrollableDivRefBro.addEventListener('scroll', handleScroll);
      // 清除事件监听
      return () => {
        scrollableDivRefBro.removeEventListener('scroll', handleScroll);
      };
    }
  }, [scrollableDivRef, scrollFlag]);

  useEffect(() => {
    if (detail.activityId) {
      // setPageNo(1);
      pageNo = 1;
      setSrollFlag(true);
      dataTableBro = [];
      initQuery();
    }
  }, [detail.activityId]);

  const handleDelete = (record: any) => {
    Modal.confirm({
      content: `确定要删除此活动？`,
      onOk() {
        dataTableBro = dataTableBro.filter((item: any) => item.id !== record.id);
        setDataTable(dataTableBro);
      },
      onCancel() {},
    });
  };

  const columns = [
    {
      title: '活动定义',
      dataIndex: 'activityId',
      key: 'activityId',
      width: 200,
      render: (text: any, _: any) => (
        <>
          {_.showRed && <span style={{ color: '#c62d2e' }}>*</span>}
          {_.activityId}
        </>
      ),
    },
    {
      title: '活动名称',
      dataIndex: 'activity',
      key: 'activity',
      width: 180,
      ellipsis: true,
    },
    {
      title: '活动有效期',
      dataIndex: 'validStartTime',
      key: 'validStartTime',
      width: 300,
      render: (text: any, _: any) => (
        <>
          {_.activityStartTime}-{_.activityEndTime}
        </>
      ),
    },
    {
      title: '运营时间',
      dataIndex: 'rankDate',
      key: 'rankDate',
      width: 120,
      // sorter: (a: any, b: any) => a.rankDate - b.rankDate,
    },
    {
      title: 'Rank Value',
      dataIndex: 'rankValue',
      key: 'rankValue',
      width: 110,
    },
    {
      title: 'TC Mix%',
      dataIndex: 'tcMix',
      key: 'tcMix',
      width: 120,
      // Number.isInteger(42);  判断是否是一个整数
      render: (text: any, record: any) => (
        <>{record.tcMix ? Number(Number(record.tcMix) * 100).toFixed(4) : 0}%</>
      ),
    },
    {
      title: 'SPT',
      dataIndex: 'spt',
      key: 'spt',
      width: 80,
    },
    {
      title: '券核销TC',
      dataIndex: 'usedTc',
      key: 'usedTc',
      width: 110,
    },
    {
      title: '券核销连带Sales',
      dataIndex: 'usedSales',
      key: 'usedSales',
      width: 145,
      render: (text: any, _: any) => <>{_.usedSales ? Number(_.usedSales) : 0}</>,
    },
    {
      title: '曝光UV',
      dataIndex: 'uv',
      key: 'uv',
      width: 90,
    },
    {
      title: '大盘TC',
      dataIndex: 'bigTc',
      key: 'bigTc',
      width: 90,
      render: (text: any, record: any) => <>{record.bigTc || 0}</>,
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 120,
      align: 'center',
      // eslint-disable-next-line @typescript-eslint/no-shadow
      render: (text: any, record: any) => (
        <div>
          <a onClick={() => handleDelete(record)}>删除</a>
        </div>
      ),
    },
  ];

  const handleSearch = (newValue: string) => {
    if (newValue) {
      fetch(newValue, setOption);
    } else {
      setOption([]);
    }
  };

  const handleChange = (newValue: any) => {
    setValueSelect(newValue);
  };

  // 通过campaignCode，添加活动
  const addActivity = async () => {
    if (isEmpty(valueSelect)) {
      message.error('请选择campaignCode');
      return;
    }

    const params: any = {
      campaignCode: valueSelect,
      pageNo: 1,
      pageSize: 10000,
      channel: channel,
    };
    setExpandLoad(true);
    const { code, data } = await activityEffect(params);
    setExpandLoad(false);
    if (code === 200 && data) {
      data.rows.forEach((item: any, index: number) => {
        if (item.activityId === detail.activityId) {
          item.showRed = true;
          setNumFlag(index);
        } else {
          item.showRed = false;
        }
      });
      dataTableBro = uniqBy([...data.rows, ...dataTableBro], 'id');
      setDataTable(dataTableBro);
    }
  };

  return (
    <>
      <div className={styles['expanded-body']} ref={scrollableDivRef}>
        <div style={{ marginBottom: 16 }}>
          <Select
            style={{ width: 200 }}
            showSearch
            allowClear
            value={valueSelect}
            placeholder="请选择campaigncode"
            defaultActiveFirstOption={false}
            showArrow={true}
            filterOption={false}
            onSearch={handleSearch}
            onChange={handleChange}
            notFoundContent={null}
            options={option}
          />
          <Button
            style={{ marginLeft: 26 }}
            type="primary"
            onClick={() => {
              addActivity();
            }}
          >
            添加
          </Button>
        </div>
        <Table
          // @ts-ignore
          columns={columns}
          dataSource={dataTable}
          pagination={false}
          scroll={{ x: 1500 }}
          loading={expandLoad}
          rowKey="id"
        />
        <div ref={childDivRef} />
      </div>
      <div ref={broDivRef} />
    </>
  );
};

export default RenderExpandedRow;
